import time
import os
from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT
from pathlib import Path


class Doc:
    tables_title = []
    exportPath = ""
    title = ""
    author = ""

    def export(self, datasource, data, col):
        # 导出word
        word = Document()
        date = time.strftime("%Y-%m-%d", time.localtime())
        # 标题
        title = "数据库设计文档" + date
        if self.title is not None and self.title != '':
            title = self.title
        word.add_heading(title, 0)
        # 作者
        if self.author is not None and self.author != '':
            author = '@' + self.author
            p = word.add_paragraph('')
            run = p.add_run(author)
            # run.bold = True
            run.italic = True
        # 循环添加设计文档
        colnum = len(col)
        index = 0
        for tables in data:
            # 添加标题
            table_title = datasource.tables[index]
            if len(self.tables_title) > index:
                if self.tables_title[index] is not None and self.tables_title[index] != '':
                    table_title = self.tables_title[index] + '(' + datasource.tables[index] + ')'
            word.add_heading(table_title)
            # 绘制表格
            table = word.add_table(rows=len(tables) + 1, cols=colnum)
            row = 0
            # 表头
            hdr_cells = table.rows[row].cells
            for i in range(len(col)):
                hdr_cells[i].text = col[i][0]
                # 设置居中 宽度自适应（貌似没效果）
                hdr_cells[i].autofit = True
                hdr_cells[i].paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
            # 内容
            for x in range(len(tables)):
                row = row + 1
                row_cells = table.rows[row].cells
                for y in range(len(tables[x])):
                    row_cells[y].text = str(tables[x][y])
                    # 设置居中 宽度自适应（貌似没效果）
                    row_cells[y].autofit = True
                    row_cells[y].paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
            index = index + 1
        # 输出文档
        docpath = self.exportPath
        if not self.exportPath.endswith('.docx'):
            docpath = docpath + os.sep + '数据库设计文档' + date
        # 循环判断是否已经有重名
        my_file = Path(docpath + '.docx')
        while my_file.exists():
            docpath = docpath + '(' + str(1) + ')'
            my_file = Path(docpath + '.docx')
        word.save(my_file)
        print("导出数据库设计文档成功！路径：" + docpath)
